import datetime
import hashlib
import os
import re
import time
import zipfile

import psutil


def current_datetime(usecs=False):
    now_t = time.time()
    if usecs:
        float_num = str(now_t).split('.')[1][:6]
        current_time = time.strftime(f'%Y-%m-%d %H:%M:%S.{float_num}',
                                     time.localtime(now_t))
    else:
        current_time = time.strftime('%Y-%m-%d %H:%M:%S',
                                     time.localtime(now_t))

    return current_time


def md5(msg):
    return hashlib.md5(msg.encode('utf-8')).hexdigest()


def tail_txt(file_path, num=3000):
    with open(file_path, 'r', encoding='utf8') as fr:
        fr.seek(0, 2)
        fr.seek(max(fr.tell() - num, 0), 0)
        last_msg = ''
        for i in fr.readlines():
            last_msg += i.strip()
        return last_msg


def new_file(file_path):
    """检查文件是否存在，存在则返回新的文件名。重命名规则：同级目录下，下划线加数字，数字可以累加.

    :param file_path: 文件路径
    :return:
    """
    if not os.path.exists(file_path):
        return file_path
    else:
        basename = os.path.basename(file_path)
        basedir = os.path.dirname(file_path)
        name, ext = os.path.splitext(basename)

        name_idx_li = re.search(r'_(\d+?$)', name)
        if name_idx_li:
            idx_start = name_idx_li.start() + 1
            new_name = f'{name[:idx_start]}{int(name[idx_start:]) + 1}'
        else:
            new_name = f'{name}_1'

        new_file_path = os.path.join(basedir, f'{new_name}{ext}')
        if os.path.exists(new_file_path):
            return new_file(new_file_path)
        else:
            return new_file_path


def kill_task(pid):
    """" Close the process corresponding to the task."""
    try:

        parent = psutil.Process(pid)
        for child in parent.children(recursive=True):
            child.kill()

        parent.kill()

        return True
    except Exception:
        return False


def zip_files(zip_full_path, compress_li, clear=True):
    z = zipfile.ZipFile(zip_full_path, 'w')
    for d in compress_li:
        z.write(d, os.path.basename(d))
        if clear:
            os.remove(d)
    z.close()


def un_zip_files(zip_full_path):
    base_path, file_name = os.path.split(zip_full_path)
    new_folder = os.path.join(base_path, os.path.splitext(file_name)[0])
    zip_file = zipfile.ZipFile(zip_full_path)
    for names in zip_file.namelist():
        zip_file.extract(names, path=new_folder)
    zip_file.close()


def regular_expressions(express: str):
    """自定义表达式运算中的header.

    :param express: 表达式
    :return: headers
    """

    def is_number(content):
        try:
            float(content)
            return True
        except ValueError:
            return False

    symbol_li = ['+', '-', '*', '/', '(', ')', ' ']

    for i in symbol_li:
        express = express.replace(i, '-')

    while '--' in express:
        express = express.replace('--', '-')

    header_li = []

    for h in express.split('-'):
        if h:
            if not is_number(h):
                header_li.append(h)

    header_li = list(sorted(set(header_li), reverse=True))
    return header_li


def delete_folder(folder_path):
    if os.path.exists(folder_path):
        if os.path.isdir(folder_path):
            for file_name in os.listdir(folder_path):
                sub_folder_path = os.path.join(folder_path, file_name)
                if os.path.isdir(sub_folder_path):
                    delete_folder(sub_folder_path)
                else:
                    os.remove(sub_folder_path)
            os.rmdir(folder_path)
        else:
            os.remove(folder_path)
    else:
        print(f'{folder_path} not found')


def folder_clear_task(folder_path_base: str):
    for i in os.listdir(folder_path_base):
        folder_path = os.path.join(folder_path_base, i)

        if os.path.isfile(folder_path):
            continue

        ctime = os.path.getctime(folder_path)

        create_date = datetime.datetime.fromtimestamp(ctime)

        # if create_date < datetime.datetime(2021, 1, 1):
        if create_date < datetime.datetime.now() - datetime.timedelta(days=15):
            print(folder_path)
            print(create_date)
            delete_folder(folder_path)


if __name__ == '__main__':
    print(current_datetime())
    print(current_datetime(True))

    result_path = r'D:\project\essay\2023\202302\breast_cancer.csv'
    print(tail_txt(result_path))

    print(new_file(result_path))

    file_path = r'D:\project\essay\2023\202306\xxx'
    zip_li = []
    for f in os.listdir(file_path):
        print(f)
        zip_li.append(os.path.join(file_path, f))

    zip_path = os.path.join(file_path, 'test.zip')

    # zip_files(zip_path, zip_li, True)
    #
    # un_zip_files(zip_path)

    print(
        regular_expressions(
            'col1 * (2 * 奥斯卡 + col11421 / 4) + col1142 + col1'))
